package com.example.mymvvmdemo.retrofit;


import android.net.Uri;


import com.example.mymvvmdemo.MyApplication;
import com.example.mymvvmdemo.constants.Constants;
import com.example.mymvvmdemo.net.model.BaseModel;
import com.example.mymvvmdemo.utils.LogUtils;
import com.example.mymvvmdemo.utils.SpUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *
 */
public class RetrofitManager {

    private Retrofit retrofit = null;
    private static RetrofitManager retrofitManager = null;
    private String baseUrl = Constants.URL_CHINA_SC;//默认生产环境

    public String getBaseUrl() {
        return baseUrl;
    }

    public void setBaseUrl(String baseU) {
        Uri uri = Uri.parse(baseU);

        String host = new Uri.Builder()
                .scheme(uri.getScheme())
                .authority(uri.getAuthority().split(":")[0])
                .path(uri.getPath())
                .query(uri.getQuery())
                .fragment(uri.getFragment())
                .build().toString();

        this.baseUrl = host;

        buildRetrofit();
    }

    private RetrofitManager() {
    }

    public static RetrofitManager getInstance() {
        if (retrofitManager == null) {
            retrofitManager = new RetrofitManager();
        }
        return retrofitManager;
    }

    public Retrofit getRetrofit() {
        if (retrofit == null)
            buildRetrofit();
        return retrofit;
    }

    private void buildRetrofit() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
        okBuilder.addInterceptor(interceptor);
        okBuilder.connectTimeout(20, TimeUnit.SECONDS);
        okBuilder.readTimeout(20, TimeUnit.SECONDS);
        okBuilder.writeTimeout(20, TimeUnit.SECONDS);
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.client(okBuilder.build());
        builder.baseUrl(baseUrl);
        LogUtils.d("baseUrl:" + baseUrl);
        builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        builder.addConverterFactory(GsonConverterFactory.create());
        retrofit = builder.build();
    }


}
